var e = getApp(), a = e.require("utils/util.js"), t = e.require("utils/api.js"), n = e.require("utils/enums.js"), i = e.require("utils/onfire.js"), r = new Date(), o = a.makeArray(1, 24), d = [], s = null, u = [ [], [] ], l = {
    MinFreightMoney: 1
}, p = null, c = !1, m = !1;

Page({
    data: {
        isBusy: !1,
        dialogType: null,
        errandType: n.ErrandTypes[0],
        errandGenderLimit: n.ErrandGenderLimits[0],
        moneyPayable: l.MinFreightMoney,
        delivererIndex: 0,
        deliveryTimes: u,
        deliveryTimeIndex: [ 0, 0 ],
        deliveryTimeValue: {
            text: "即刻出发",
            value: null
        },
        address: null,
        carts: {},
        expiredTimes: o,
        expiredIndex: o.length - 1,
        expiredValue: 24,
        remarkValue: null,
        couponValidCount: 0,
        couponValue: null,
        popupType: "none",
        acceptAgreement: !0,
        expiredTime: null,
        model: l
    },
    onLoad: function(e) {
        s = e, this.loadData(e);
    },
    onReady: function() {
        var a = this;
        e.callAuthorize(a, function() {
            m = !0;
        });
    },
    onShow: function() {
        e.getStorage("cart")[s.id] || wx.navigateBack();
    },
    onHide: function() {},
    onUnload: function() {
        i.un("selectAddress");
    },
    onPullDownRefresh: function() {},
    onReachBottom: function() {},
    onShareAppMessage: function() {},
    onAuthorizeCallback: function(a) {
        var t = this;
        if (a.detail.userInfo) {
            t.setData({
                dialogType: null
            });
            e.authorizeCallback(t, a.detail.userInfo);
        }
    },
    loadData: function(a) {
        var n = this, i = e.getStorage("cart")[a.id];
        n.setData({
            carts: i
        }), t.orderTakeoutPrepare({
            shopId: a.id
        }, function(e) {
            c = !0, l = e, u = n.getPickerTimes(0, l.ErrandTimeRangeBegin || "8:00", l.ErrandTimeRangeEnd || "22:00"), 
            n.setData({
                model: l,
                address: l.AddressInfo,
                deliveryTimes: u
            }), n.updateMoneyPayable();
        });
    },
    updateMoneyPayable: function() {
        var e = this, a = l.MinFreightMoney;
        1 == e.data.delivererIndex && (a += e.data.model.DiffSpDevPrice), e.data.couponInfo && (a -= e.data.couponInfo.Money);
        for (var t in e.data.carts.Items) {
            var n = e.data.carts.Items[t];
            a += n.Quantity * n.Price;
        }
        e.setData({
            moneyPayable: a > 0 ? a : 0
        });
    },
    onAddressTap: function(e) {
        t.userSaveFormId({
            formId: e.detail.formId
        });
        var a = this, n = [ "user" ];
        i.un("selectAddress"), i.on("selectAddress", function(e) {
            a.setData({
                address: e
            });
        }), wx.navigateTo({
            url: "../../common/location/select?index=1&tabs=" + n.join(",")
        });
    },
    onDelivererChange: function(e) {
        var t = this, n = parseInt(e.detail.value);
        4 == t.data.errandType.Value && (n = 1, a.toast("目前代寄物品仅限平台专员配送")), t.setData({
            delivererIndex: n
        }), t.updateMoneyPayable();
    },
    getPickerTimes: function(e, t, n) {
        var i = [ [], [] ];
        t = t || "00:00", n = n || "23:30", i[0].push({
            text: "今天",
            value: 0
        });
        for (g = 0; g < l.ErrandTimeRangeDays - 1; ++g) {
            var o = 0 == g ? "明天" : 1 == g ? "后天" : "";
            i[0].push({
                text: (o.length ? o + "（" : o) + a.formatDate(a.addDate(r, g + 1)) + (o.length ? "）" : o),
                value: g + 1
            });
        }
        var d = null;
        if (e) {
            var s = a.addDate(r, 1), u = parseInt(t.split(":")[0]), p = parseInt(t.split(":")[1]);
            d = new Date(s.getFullYear(), s.getMonth(), s.getDate(), u, p, 0);
        } else {
            d = a.addDate(r, 30, "m"), i[1].push({
                text: "即刻出发",
                value: null
            });
            var c = 30 - d.getMinutes() % 30;
            d = a.addDate(a.addDate(d, c, "m"), -d.getSeconds(), "s");
        }
        for (var m = parseInt(n.split(":")[0]), v = parseInt(n.split(":")[1]), f = new Date(d.getFullYear(), d.getMonth(), d.getDate(), m, v, 0), y = d, g = 0; y < f; g++) y = a.addDate(d, 30 * g, "m"), 
        i[1].push({
            text: a.formatDate(y, "minute", "time"),
            value: y
        });
        return i;
    },
    onDeliveryTimeChange: function(e) {
        var a = this, t = e.detail.value[0], n = e.detail.value[1];
        u[0][t], u[1][e.detail.value[1]];
        a.setData({
            deliveryTimeValue: {
                text: (0 == t && 0 == n ? "" : u[0][t].text + " ") + u[1][n].text,
                value: u[1][n].value
            }
        });
    },
    onDeliveryTimeColumnChange: function(e) {
        if (0 == e.detail.column) {
            var a = this, t = a.getPickerTimes(e.detail.value, a.data.model.ErrandTimeRangeBegin || "8:00", a.data.model.ErrandTimeRangeEnd || "22:00");
            u.splice(0, u.length), u.push(t[0]), u.push(t[1]), a.setData({
                deliveryTimes: u
            });
        }
    },
    onExpiredTap: function() {
        this.setData({
            popupType: "expired"
        });
    },
    onPopupCancel: function() {
        this.setData({
            popupType: "none"
        });
    },
    onPopupConfirm: function() {
        var e = this, a = e.data.popupType;
        setTimeout(function() {
            e.setData({
                popupType: "none"
            }), setTimeout(function() {
                "expired" == a ? e.setData({
                    expiredValue: o[e.data.expiredIndex]
                }) : "remark" == a && e.setData({
                    remarkValue: p
                });
            }, 200);
        }, 50);
    },
    onExpiredSliderChange: function(e) {
        this.setData({
            expiredIndex: e.detail.value
        });
    },
    onLimitTap: function(e) {
        var a = this;
        wx.showActionSheet({
            itemList: n.getNames(n.ErrandGenderLimits),
            success: function(e) {
                a.setData({
                    errandGenderLimit: n.ErrandGenderLimits[e.tapIndex]
                });
            },
            fail: function(e) {
                console.log(e.errMsg);
            }
        });
    },
    onRemarkTap: function() {
        this.setData({
            popupType: "remark"
        });
    },
    onRemarkContentChanged: function(e) {
        p = e.detail.value;
    },
    onCouponTap: function() {
        var e = this;
        i.un("CouponSelect"), i.one("CouponSelect", function(a) {
            var t = 0;
            d.splice(0, d.length);
            for (var n in a) t += a[n].Money, d.push(a[n]);
            e.setData({
                couponValue: t
            });
        }), wx.navigateTo({
            url: "../../mine/coupon/index?list=true"
        }), i.fire("CouponLoad", e.data.model.Coupons);
    },
    onFormSubmit: function(r) {
        t.userSaveFormId({
            formId: r.detail.formId
        });
        var o = this;
        if (e.globalData.userInfo.Mobile) {
            var u = [], p = 0;
            for (var c in o.data.carts.Items) {
                var m = o.data.carts.Items[c];
                u.push({
                    CommodityId: m.Id,
                    Money: m.Money,
                    Price: m.Price,
                    Quantity: m.Quantity
                }), p += m.Price * m.Quantity;
            }
            var v = {
                Type: n.OrderTypes[0].Value,
                Money: p,
                MoneyFreight: l.MinFreightMoney,
                LimitDeliverer: o.data.delivererIndex + 1,
                LimitDelivererGender: o.data.errandGenderLimit.Value,
                ShopId: s.id,
                Items: u,
                OrderAddressList: [ {
                    AddressId: o.data.address.Id,
                    Address: o.data.address.Linkman + "(" + o.data.address.Phone + ")",
                    Description: o.data.address.Address,
                    Longitude: o.data.address.Longitude,
                    Latitude: o.data.address.Latitude,
                    IsOutSide: o.data.address.IsOutSide
                } ],
                CouponList: [],
                ExpectTime: o.data.deliveryTimeValue && o.data.deliveryTimeValue.value,
                ExpiredMinutes: 60 * o.data.expiredValue,
                MoneyPayment: o.data.moneyPayable,
                Remark: o.data.remarkValue || ""
            };
            for (var c in d) v.CouponIds.push(d[c].Id);
            if (v.OrderAddressList.length) {
                var f = function() {
                    var a = e.getStorage("cart");
                    delete a[s.id], a.save();
                };
                o.setData({
                    isBusy: !0
                }), t.orderCommit(v, function(e) {
                    t.orderPayment({
                        id: e
                    }, function(a) {
                        i.fire("refreshHomeOrders"), f(), wx.navigateTo({
                            url: "../../order/_/info?id=" + e
                        }), o.setData({
                            isBusy: !1
                        });
                    }, function() {
                        f(), wx.navigateTo({
                            url: "../../order/_/info?id=" + e
                        }), o.setData({
                            isBusy: !1
                        });
                    });
                });
            } else a.toast("请选择配送地址");
        } else wx.navigateTo({
            url: "../../mine/info/bindmobile"
        });
    },
    onServiceContractLink: function() {
        var e = this;
        wx.navigateTo({
            url: "../../common/content/web?url=" + encodeURIComponent("/article/info?id=" + e.data.model.ErrandServiceArticleId)
        });
    }
});